//
//  BaseViewController.m
//  youlele
//
//  Created by wujian on 2017/12/17.
//  Copyright © 2017年 zongquankeji. All rights reserved.
//

#import "AppBaseViewController.h"
#import "FindViewController.h"

@interface AppBaseViewController ()

@end

@implementation AppBaseViewController


-(void)viewWillAppear:(BOOL)animated{
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    //控制整个功能是否启用。
    manager.enable = YES;
    //控制点击背景是否收起键盘
    manager.shouldResignOnTouchOutside = YES;
    manager.enableAutoToolbar = NO;
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    self.navigationController.navigationBar.translucent = NO;
    
    self.navBarBgAlpha = @"1.0";
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.view.backgroundColor = CSWhiteColor;
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.noDataView = [NoDataView shareInstance];
    
    self.noDataView.noticeLabel.text = @"暂无数据";        
    
    [NotificationCenter addObserver:self selector:@selector(netWorkChanged:) name:@"NewWorkChanged" object:nil];
}

/**
 左标题显示
 */
-(void)showLeftTitleWithTitle:(NSString *)titleName{
    
    UIBarButtonItem *leftButtonItem = [[UIBarButtonItem alloc] initWithTitle:titleName style:UIBarButtonItemStylePlain target:self action:@selector(leftBtnClick)];
    
    [leftButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:CSWhiteColor,NSFontAttributeName:kFont16} forState:UIControlStateNormal];
    [leftButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:CSWhiteColor,NSFontAttributeName:kFont16} forState:UIControlStateHighlighted];
    
    self.navigationItem.leftBarButtonItem = leftButtonItem;
}

/**
 左标题显示
 */
-(void)showLeftTitleWithTitle:(NSString *)titleName withColor:(UIColor *)color{
    
    UIBarButtonItem *leftButtonItem = [[UIBarButtonItem alloc] initWithTitle:titleName style:UIBarButtonItemStylePlain target:self action:@selector(leftBtnClick)];
    
    [leftButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:color,NSFontAttributeName:kFont16} forState:UIControlStateNormal];
    [leftButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:color,NSFontAttributeName:kFont16} forState:UIControlStateHighlighted];
    
    self.navigationItem.leftBarButtonItem = leftButtonItem;
}

/**
 右侧图片显示
 */
-(void)showRightImageWithImageName:(NSString *)name{
    
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:name]
                                                                               imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnClick)];
    self.navigationItem.rightBarButtonItem = rightButtonItem;
}


/**
 坐侧图片显示
 */
-(void)showLeftImageWithImageName:(NSString *)name{
    
    UIBarButtonItem *leftButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:name]
                                                                               imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(leftBtnClick)];
    self.navigationItem.leftBarButtonItem = leftButtonItem;
}

/**
 右侧标题显示
 */
-(void)showRightTitleWithTitle:(NSString *)titleName{
    
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithTitle:titleName style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnClick)];
    
    [rightButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:CSBlackColor,NSFontAttributeName:MidFont} forState:UIControlStateNormal];
    [rightButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:CSBlackColor,NSFontAttributeName:MidFont} forState:UIControlStateHighlighted];
    
    self.navigationItem.rightBarButtonItem = rightButtonItem;
}

/**
 右侧标题显示
 */
-(void)showRightTitleWithTitle:(NSString *)titleName withColor:(UIColor *)color{
    
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithTitle:titleName style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnClick)];
    
    [rightButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:color,NSFontAttributeName:MidFont} forState:UIControlStateNormal];
    [rightButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:color,NSFontAttributeName:MidFont} forState:UIControlStateHighlighted];
    
    self.navigationItem.rightBarButtonItem = rightButtonItem;
}

/**
 获取视频第一帧
 */
- (UIImage*) getVideoPreViewImage:(AVAsset *)asset
{
    AVAssetImageGenerator *assetGen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    
    assetGen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [assetGen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *videoImage = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    return videoImage;
}

/**
 *  生成图片
 *
 *  @param color  图片颜色
 *  @param height 图片高度
 *
 *  @return 生成的图片
 */
- (UIImage*) GetImageWithColor:(UIColor*)color andHeight:(CGFloat)height
{
    CGRect r= CGRectMake(0.0f, 0.0f, 1.0f, height);
    UIGraphicsBeginImageContext(r.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, r);
    
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return img;
}


/**
 显示一个目录下面的所有文件
 */
-(void)showFiles:(NSString *)path{
    
    // 1.判断文件还是目录
    
    NSFileManager * fileManger = [NSFileManager defaultManager];
    
    BOOL isDir = NO;
    
    BOOL isExist = [fileManger fileExistsAtPath:path isDirectory:&isDir];
    
    if (isExist) {
        
        // 2. 判断是不是目录
        
        if (isDir) {
            
            NSArray * dirArray = [fileManger contentsOfDirectoryAtPath:path error:nil];
            
            NSString * subPath = nil;
            
            for (NSString * str in dirArray) {
                
                subPath  = [path stringByAppendingPathComponent:str];
                
                BOOL issubDir = NO;
                
                [fileManger fileExistsAtPath:subPath isDirectory:&issubDir];
                
                [self showFiles:subPath];
                
            }
            
        }else{
            
            NSLog(@"%@",path);
            
        }
        
    }else{
        
        NSLog(@"你打印的是目录或者不存在");
        
    }
    
}


/**
 缓存音乐目录是否包含音乐
 */
-(BOOL)contentFile:(NSString *)filePath{
    
    NSString *cachDict = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) firstObject];
    
    //文件夹picture
    NSString *path = [cachDict stringByAppendingPathComponent:@"music"];
    
    // 1.判断文件还是目录
    
    NSFileManager * fileManger = [NSFileManager defaultManager];
    
    BOOL isDir = NO;
    
    BOOL isExist = [fileManger fileExistsAtPath:path isDirectory:&isDir];
    
    if (isExist) {
        
        // 2. 判断是不是目录
        
        if (isDir) {
            
            NSArray * dirArray = [fileManger contentsOfDirectoryAtPath:path error:nil];
            
            NSString * subPath = nil;
            
            for (NSString * str in dirArray) {
                
                subPath  = [path stringByAppendingPathComponent:str];
                
                if ([subPath isEqualToString:filePath]) {
                    
                    return YES;
                }
            }
            
        }else{
            
            NSLog(@"%@",path);
            
            return NO;
            
        }
        
    }
    
    return NO;
}


/**
 处理播放的Url
 */
-(NSString *)dealWithUrl:(NSString *)url{
    
    NSString *cachDict = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) firstObject];
    
    NSFileManager * fileManager =[NSFileManager defaultManager];
    
    //文件夹picture
    NSString *testDirectory = [cachDict stringByAppendingPathComponent:@"music"];
    
    if([fileManager fileExistsAtPath:testDirectory])
    {
        
        NSString *urlLastName = [[url componentsSeparatedByString:@"/"] lastObject];
        
        NSString *fileName = [NSString stringWithFormat:@"p1.pstatp.com-obj-%@.mp4",urlLastName];
        
        NSString *localFileName = [testDirectory stringByAppendingPathComponent:fileName];
        
        if ([self contentFile:localFileName]) {
            
            return localFileName;
        }
    }
    
    return url;
}




/**
 右侧按钮点击事件
 */
-(void)rightBtnClick{
    
    //调用子类
}

/**
 左侧按钮点击事件
 */
-(void)leftBtnClick{
    
    //调用子类
}


#pragma mark -- 获取视频／音频文件的总时长
- (CGFloat)getFileDuration:(NSURL*)URL {
    NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:URL options:opts];
    
    CMTime duration = asset.duration;
    float durationSeconds = CMTimeGetSeconds(duration);
    
    return durationSeconds;
}

#pragma mark - 输出路径
- (NSURL *)exportAudioMixPath {
    
    NSString *path = MoveFilePath;
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if(![fileManager fileExistsAtPath:path]) {
        [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *nowTimeStr = [formatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:0]];
    NSString *fileName = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_mix.mp4",nowTimeStr]];
    return [NSURL fileURLWithPath:fileName];
}

/**
 # 变色
 */
-(NSMutableAttributedString *)attributeWithStr:(NSString *)str{
    
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:str];
    
    [attStr addAttribute:NSForegroundColorAttributeName value:[UIColor yellowColor] range:[str rangeOfString:@"#"]];
    
    return attStr;
}


/**
 弹起登录
 */
-(void)jumpToLogin{
    
//    UserNavigationController *nav = [[UserNavigationController alloc] initWithRootViewController:[[LoginViewController alloc] init]];
//    
//    [self.tabBarController presentViewController:nav animated:YES completion:nil];
    
}

/**
 网络状态监听
 */
-(void)netWorkChanged:(NSNotification *)sender{
    
    NSDictionary *dict = sender.userInfo;
    
    int status = [[dict objectForKey:@"status"] intValue];
    
    if (status == 0) {
        
        [MBProgressHUD showText:@"当前无网络"];
    }
    else if (status == 2){
        
        if ([self isKindOfClass:[FindViewController class]]) {
            
            [NotificationCenter postNotificationName:@"ReloadHomeData" object:nil];
        }
        //[MBProgressHUD showText:@"已切换到WIFI网络"];
    }
    else if (status == 1){
        
        [MBProgressHUD showText:@"已切换到移动网络"];
        
        if ([self isKindOfClass:[FindViewController class]]) {
            
            [NotificationCenter postNotificationName:@"ReloadHomeData" object:nil];
        }
    }
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

-(BOOL)prefersStatusBarHidden{
    return NO;
}

@end
